package com.cachopoid.activity;


import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import ws.JSONManager;
import ws.JsonParsers;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cachopoid.R;
import com.cachopoid.utils.Constantes;
import com.cachopoid.vo.CachopoVO;
import com.cachopoid.vo.EstablecimientoVO;

import fragments.FragmentBusqueda;
import fragments.FragmentEnviaIncidencia;
import fragments.FragmentEventos;
import fragments.FragmentRankingCachopos;
import fragments.NavigationDrawerFragment;

public class MainActivity extends Activity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks{

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    static ListView listViewRanking;
    private static ProgressBar pbarProgreso;
    Constantes cons = new Constantes();
	static JSONObject jsonResult = new JSONObject();
	static ArrayList<CachopoVO> listaRankingCachoposGlobal;
	static ArrayList<EstablecimientoVO> ListaRankingEstablecimientosGlobal;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
        mNavigationDrawerFragment = (NavigationDrawerFragment)
               getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();
       // pbarProgreso = (ProgressBar) findViewById(R.id.pbarProgresoRanking);
        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
       
    }
   
    
    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
    	
      FragmentManager fragmentManager = getFragmentManager();
       
        switch(position){
        
        case 0:
        	
        	FragmentEventos unf = new FragmentEventos();
        	fragmentManager.beginTransaction()
            .replace(R.id.container, unf.newInstance(position + 1, this))
            .addToBackStack(null)
            .commit();
        	
        break;
        
        /*********************/
        /**RANKING CACHOPOS**/
        /********************/
        
    	case 1:
    		

            fragmentManager.beginTransaction()
            .replace(R.id.container, FragmentRankingCachopos.newInstance(position + 1,this))
            .addToBackStack(null)
            .commit();
            
    	break;
    	 
    	 /*********************/
         /*******BUSQUEDA*****/
         /********************/
    	
    	case 2:  	
            fragmentManager.beginTransaction()
            .replace(R.id.container, FragmentBusqueda.newInstance(position + 1, this))
            .addToBackStack(null)
            .commit();
    	break;
    	
    	
    	/******************************/
        /*******ENVIAR INCIDENCIAS*****/
        /******************************/
    	
    	case 3:
    		
    		 fragmentManager.beginTransaction()
             .replace(R.id.container, FragmentEnviaIncidencia.newInstance(position + 1))
             .addToBackStack(null)
             .commit();
    		 
    	break;
    	
        }
        
    }

    public void onSectionAttached(int number) {
        switch (number) {
        	case 1:
	            mTitle = getString(R.string.eventos);
	            break;
            case 2:
                mTitle = getString(R.string.ranking);
                break;
            case 3:
                mTitle = getString(R.string.buscar);
                break;
            case 4:
                mTitle = getString(R.string.envia_incidencia);
                break;
        }
    }

    /**
     * Cambia el nombre al titulo del action
     */
    public void restoreActionBar() {
        android.app.ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {

            case R.id.action_settings:
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    /**
     * Función para llamar al establecimiento
     * @param view
     */
    public void llamarTelefono(View view){
		try {
			Intent intent = new Intent(Intent.ACTION_CALL);
      		TextView telefono = (TextView)findViewById(R.id.tlfEstablecimiento);
			intent.setData(Uri.parse("tel:"+telefono.getText().toString()));
			startActivity(intent);
		} catch (ActivityNotFoundException activityException) {
			Log.e("dialing-example", "Call failed", activityException);
		}
	}
    
    /**
     * Función para mostrar la ubicación del establecimiento
     * @param view
     */
    
    public void mostrarUbicacion(View view){
		try {
			Intent intent = new Intent(MainActivity.this,MapaActivity.class);
			//Coordenadas
			TextView latitudEstab = (TextView)findViewById(R.id.latitudEstab);
			TextView longitudEstab = (TextView)findViewById(R.id.longitudEstab);
			intent.putExtra(Constantes.LATITUD, latitudEstab.getText());
			intent.putExtra(Constantes.LONGITUD, longitudEstab.getText());
			startActivity(intent);
		} catch (ActivityNotFoundException activityException) {
			Log.e("dialing-example", "Call failed", activityException);
		}
	}

 
}

  
